let searchBack = document.querySelector("#searchBack");
let searchResultBack = document.querySelector("#searchResultBack");
let searchFrame = document.querySelector("#searchFrame");
let searchRecommendList = document.querySelector(".searchRecommendList")

//  searchResult page
let resultSongList = document.querySelector("#resultSongList");
let searchResultFrame = document.querySelector("#searchResultFrame");

let searchRecommendArray = [];
let keywords = "";
let realRecommendKeyword = "华北浪漫革命";
let offsets = 1;

//  点击返回
searchBack.addEventListener("click", evt => {
    history.back();
})
searchResultBack.addEventListener("click", evt => {
    history.back();
})


//  监听输入，获取搜索建议
searchFrame.addEventListener("input", async evt => {
    let value = searchFrame.value;
    keywords = value
    let searchResult = await utils.request(
        "get",
        `/search/suggest?keywords=${value}`
    );
    console.log(searchResult)
    if (searchResult.code === 200) {
        let data = searchResult.result.songs;
        searchRecommendList.innerHTML = "";
        for (let i = 0; i < data.length; i ++) {
            const element = data[i];
            searchRecommendArray.push({
                songName: element.name,
                songId: element.id
            });
            searchRecommendList.innerHTML += `
                <li
                class="searchRecommendItem"
                data-keywords="${element.name}">
                    <a href="#">
                        <i>&#xe611;</i>
                        <span>${element.name}</span>
                    </a>
                </li>`;
        }
        clickToSearch(data);
    }
});

searchFrame.addEventListener("keyup", async evt => {
    if (evt.key === "Enter") {
        resultSongList.innerHTML = "";
        if (searchFrame.value !== "") {
            utils.navigateTo("#searchResult");
            let value = searchFrame.value;
            let data = await getSearchData(value, 1);
            addDataToSearchPage(data);
        } else {
            //为空情况下,搜索默认的关键词
            utils.navigateTo("#searchResult");
            console.log(realRecommendKeyword)
            let data = await getSearchData(realRecommendKeyword, 1);
            resultSongList.innerHTML = "";
            addDataToSearchPage(data);
        }
        //首页的歌曲列表点击
        let searchResultLi = document.querySelectorAll(".searchResultLi");
        clickToMusicPlayer(searchResultLi);
    }
})

resultSongList.addEventListener("scroll", async evt => {
    let scrollTop = resultSongList.scrollTop;
    let fullUlElementHeight = resultSongList.scrollHeight - resultSongList.clientHeight;

    if (scrollTop >= fullUlElementHeight) {
        let data = await getSearchData(keywords, ++ offsets);
        addDataToSearchPage(data);
        let searchResultLi = document.querySelectorAll(".searchResultLi");
        clickToMusicPlayer(searchResultLi);
    }
});

searchResultFrame.addEventListener("keyup", async evt => {
    if (evt.key === "Enter") {
        resultSongList.innerHTML = "";
        if (searchResultFrame.value !== "") {
            let value = searchResultFrame.value;
            keywords = value;
            let data = await getSearchData(value, 1);
            addDataToSearchPage(data);
        } else {
            //为空情况下,搜索默认的关键词
            keywords = realRecommendKeyword;
            let data = await getSearchData(realRecommendKeyword, 1);
            // resultSongList.innerHTML = "";
            addDataToSearchPage(data);
        }
        //首页的歌曲列表点击
        let searchResultLi = document.querySelectorAll(".searchResultLi");
        clickToMusicPlayer(searchResultLi);
    }
});



/**
 * 点击搜索页元素前往搜索结果页
 * @param data
 */
function clickToSearch(data) {
    let searchRecommendItemList = document.querySelectorAll(".searchRecommendItem");
    for (let i = 0; i < searchRecommendItemList.length; i++) {
        const element = searchRecommendItemList[i];
        console.log(data)
        element.addEventListener("click", async evt => {
            let searchKeywords = data[i].name;
            utils.navigateTo("#searchResult");
            let requestData = await getSearchData(searchKeywords, 1);
            console.log(requestData);
            resultSongList.innerHTML = "";
            addDataToSearchPage(requestData);
            let searchResultLi = document.querySelectorAll(".searchResultLi");
            clickToMusicPlayer(searchResultLi);
        })
    }
}

async function getSearchData(searchKeywords, offsets) {
    let timestamp = Date.now();
    let result = await utils.request(
        "get",
        `/cloudsearch?keywords=${keywords}&limit=60&offset=${offsets-1+10}&timestamp=${timestamp}`
    );
    if (result.code === 200) {
        return result.result.songs;
    }
}

function addDataToSearchPage(data) {
    for (let i = 0; i < data.length; i++) {
        const element = data[i];
        resultSongList.innerHTML += `
            <li class="searchResultLi" data-id="${element.id}">
                <img data-src="${element.al.picUrl}?param=100y100" src="./assets/img/musicPlaylist/toby.jpg"/>
                <div class="songInfo">
                    <p class="songName">${element.name}</p>
                    <br/>
                    <p class="songAuthor">${element.ar[0].name}</p>
                </div>
            </li>`;
    }
    let imgArray = document.querySelectorAll(".searchResultLi>img");
    utils.imgLazyLoad(imgArray);
}

//歌曲点击进入播放
function clickToMusicPlayer(li) {
    li.forEach((element) => {
        element.addEventListener("click", (e) => {
            let musicId = element.getAttribute("data-id");
            //点击后跳转到播放页面
            utils.musicPlayerLoader([musicId], musicId);
            utils.navigateTo("#musicPlayer");
        });
    });
}